package org.jeecg.modules.demo.cashier;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.mall.api.MallHelloApi;
import org.jeecg.modules.demo.mall.entity.YxStoreProduct;
import org.jeecg.modules.demo.mall.entity.YxSystemUserLevel;
import org.jeecg.modules.demo.mall.entity.YxUser;
import org.jeecg.modules.demo.weixin.dto.PayDto;
import org.jeecg.modules.demo.weixin.entity.*;
import org.jeecg.modules.demo.weixin.payorder.service.IPayOrderService;
import org.jeecg.modules.demo.weixin.smtdev.service.ISmtDevService;
import org.jeecg.modules.demo.weixin.smtmerchantshoprecord.service.ISmtMerchantShopRecordService;
import org.jeecg.modules.demo.weixin.smtoncecarddeduction.service.ISmtOnceCardDeductionService;
import org.jeecg.modules.demo.weixin.smtoncecardinfo.service.ISmtOnceCardInfoService;
import org.jeecg.modules.demo.weixin.smtoncecardusers.service.ISmtOnceCardUsersService;
import org.jeecg.modules.demo.weixin.smtsplitmerchant.service.ISmtSplitMerchantService;
import org.jeecg.modules.demo.weixin.smtyuyuelist.service.ISmtYuyueListService;
import org.jeecg.modules.demo.weixin.smtyuyueuser.service.ISmtYuyueUserService;
import org.jeecg.modules.demo.weixin.util.MD5Util;
import org.jeecg.modules.demo.weixin.util.NoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zhanglu
 * TODO
 * @date 2023/10/29  19:34
 * Description: 类
 */
@RestController
@RequestMapping("/weixin/cashierOrder/cashierorder")
@Slf4j
public class CashierOrderController extends JeecgController<PayOrder, IPayOrderService> {
    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private ISmtOnceCardInfoService smtOnceCardInfoService;

    @Autowired
    private ISmtOnceCardUsersService smtOnceCardUsersService;
    @Autowired
    private ISmtMerchantShopRecordService smtMerchantShopRecordService;

    @Autowired
    private ISmtYuyueListService yuyueListService;

    @Autowired
    private ISmtYuyueUserService yuyueUserService;
    @Autowired
    private ISmtOnceCardDeductionService smtOnceCardDeductionService;

    @Autowired
    private MallHelloApi mallHelloApi;

    @Autowired
    private ISmtDevService smtDevService;


    /**
     * 添加
     *
     * @param payOrder
     * @return
     */
    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping(value = "/addOrder")
    public Result<String> add(@RequestBody PayOrder payOrder) {
        payOrder.setMerchantId(payOrder.getMerId());
        payOrder.setOrderNo(NoUtil.getOrderNo());
        if (!payOrderService.save(payOrder)) {
            return Result.error("添加失败!");
        }
        return Result.OK("添加成功！");
    }

    /**
     * 订单查询
     *
     * @param payOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     * @throws ParseException
     */
    //@AutoLog(value = "pay_order-分页列表查询")
    @ApiOperation(value = "pay_order-分页列表查询", notes = "pay_order-分页列表查询")
    @GetMapping(value = "/queryOrder")
    public Result<IPage<PayOrder>> queryPageList(PayOrder payOrder,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) throws ParseException {
        Page<PayOrder> page = new Page<PayOrder>(pageNo, pageSize);
        QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isBlank(payOrder.getMerId())) {
            return Result.error("门店id未传");
        }

        //根据场次id获取门店对应订单
//        List<String> yuyueIds = yuyueListService.queryMerList(payOrder.getMerId());
        //获取设备
        LambdaQueryWrapper<SmtDev> smtDevLambdaQueryWrapper = new LambdaQueryWrapper<>();
        smtDevLambdaQueryWrapper.eq(SmtDev::getMerchantId, payOrder.getMerId());
        List<SmtDev> smtDevList = smtDevService.list(smtDevLambdaQueryWrapper);
//        if (CollectionUtils.isEmpty(yuyueIds)) {
//            return Result.OK(page);
//        }
        //如果yuyueIds未null 则没有数据 且 ordertype不等于null
        if (payOrder.getOrderType() != null) {

            if (!CollectionUtils.isEmpty(smtDevList)) {
                List<String> devList = smtDevList.stream().map(SmtDev::getDevCode).collect(Collectors.toList());
                queryWrapper.and(payOrderQueryWrapper -> payOrderQueryWrapper.in("dev_code", devList).or().eq("merchant_id", payOrder.getMerId()));
            } else queryWrapper.eq("merchant_id", payOrder.getMerId());

            queryWrapper.eq("order_type", payOrder.getOrderType());
        }
        //如果订单类型为空则   排期和不排期都显示
        if (payOrder.getOrderType() == null) {

            if (!CollectionUtils.isEmpty(smtDevList)) {
                List<String> devList = smtDevList.stream().map(SmtDev::getDevCode).collect(Collectors.toList());
                queryWrapper.and(payOrderQueryWrapper -> payOrderQueryWrapper.in("dev_code", devList).or().eq("merchant_id", payOrder.getMerId()));
            }
            queryWrapper.and(payOrderQueryWrapper -> payOrderQueryWrapper.eq("merchant_id", payOrder.getMerId()));
        }

        if (payOrder.getUserId() != null) {
            queryWrapper.eq("user_id", payOrder.getUserId());
        }
        //判断当前收银员的权限
        if (payOrder.getRechargeUser() != null) {
            queryWrapper.eq("recharge_user", payOrder.getRechargeUser());
        }
        if (StringUtils.isNotBlank(payOrder.getPayStatus())) {
            queryWrapper.eq("pay_status", payOrder.getPayStatus());
        }
        if (StringUtils.isNotBlank(payOrder.getStartTime())) {
            queryWrapper.apply("DATE(create_time) like '" + payOrder.getStartTime() + "'");
        }
        queryWrapper.orderByDesc("create_time");
        IPage<PayOrder> pageList = payOrderService.page(page, queryWrapper);
        if (CollectionUtils.isEmpty(pageList.getRecords())) {
            return Result.OK(pageList);
        }
        //
        List<PayOrder> payOrders = payOrderService.queryUserdetails(pageList.getRecords(), payOrder.getMerId());
        return Result.OK(pageList.setRecords(payOrders));
    }


    /**
     * 查询每个用户的储值订单记录
     *
     * @param pageNo
     * @param pageSize
     * @return
     * @throws ParseException
     */
    @GetMapping(value = "/queryOrderRecord")
    public Result<IPage<PayOrder>> queryOrderRecord(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    @RequestParam(name = "uid") Integer uid,
                                                    @RequestParam(name = "orderType") Integer orderType,
                                                    String merId) throws ParseException {
        QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", uid);
        if (orderType != null) {
            queryWrapper.eq("order_type", orderType);
        }
        queryWrapper.eq("merchant_id", merId);
        queryWrapper.orderByDesc("create_time");
        Page<PayOrder> page = new Page<PayOrder>(pageNo, pageSize);
        IPage<PayOrder> pageList = payOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 次卡订单添加
     *
     * @param payOrder
     * @return
     */
    @ApiOperation(value = "pay_order-添加", notes = "pay_order-添加")
    @PostMapping(value = "/addCard")
    public Result<String> addCard(@RequestBody PayOrder payOrder) {
        payOrderService.save(payOrder);
        return Result.OK("添加成功！");
    }


    /**
     * 通过id查询详情
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<PayOrder> queryById(@RequestParam(name = "id", required = true) Integer id) {
        PayOrder payOrder = payOrderService.getById(id);
        if (payOrder == null) {
            return Result.error("未找到对应数据");
        }
        YxUser yxUser = mallHelloApi.queryUser(payOrder.getUserId());
        if (yxUser != null) {
            YxSystemUserLevel yxSystemUserLevel = mallHelloApi.queryLevel(yxUser.getLevel());
            if (yxSystemUserLevel != null) {
                payOrder.setLevel(yxSystemUserLevel.getGrade());
                payOrder.setLevelName(yxSystemUserLevel.getName());
            }
            payOrder.setUsername(yxUser.getRealName());
            payOrder.setPhone(yxUser.getPhone());

        }
        if (payOrder.getOrderType().equals(7)) {
            LambdaQueryWrapper<SmtOnceCardDeduction> deductionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            deductionLambdaQueryWrapper.eq(SmtOnceCardDeduction::getOrderNo, payOrder.getOrderNo());
            SmtOnceCardDeduction smtOnceCardDeduction = smtOnceCardDeductionService.getOne(deductionLambdaQueryWrapper);
            payOrder.setSmtOnceCardDeduction(smtOnceCardDeduction);
        }
        if (payOrder.getOrderType().equals(6)) {
            LambdaQueryWrapper<SmtMerchantShopRecord> merchantShopRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            merchantShopRecordLambdaQueryWrapper.eq(SmtMerchantShopRecord::getOrderId, payOrder.getId());
            List<SmtMerchantShopRecord> merchantShopRecords = smtMerchantShopRecordService.list(merchantShopRecordLambdaQueryWrapper);
            payOrder.setShopRecordList(merchantShopRecords);
        }
        if (payOrder.getOrderType().equals(2)) {
            LambdaQueryWrapper<SmtOnceCardUsers> smtOnceCardUsersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            smtOnceCardUsersLambdaQueryWrapper.eq(SmtOnceCardUsers::getOrderId, payOrder.getId());
            List<SmtOnceCardUsers> smtOnceCardUsers = smtOnceCardUsersService.list(smtOnceCardUsersLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(smtOnceCardUsers)) {
                smtOnceCardUsers.forEach(cardUser -> {
                    YxStoreProduct yxStoreProduct = mallHelloApi.queryName(Integer.valueOf(cardUser.getGoodsId()));
                    if (yxStoreProduct != null) {
                        cardUser.setGoodName(yxStoreProduct.getStoreName());
                    }
                });
            }
            payOrder.setCardUsers(smtOnceCardUsers);
        }
        if (payOrder.getOrderType().equals(3) && payOrder.getPayStatus().equals(5)) {
            LambdaQueryWrapper<SmtMerchantShopRecord> merchantShopRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            merchantShopRecordLambdaQueryWrapper.eq(SmtMerchantShopRecord::getOrderId, payOrder.getId());
            List<SmtMerchantShopRecord> merchantShopRecords = smtMerchantShopRecordService.list(merchantShopRecordLambdaQueryWrapper);
            payOrder.setStoreRecordList(merchantShopRecords);
        }
        return Result.OK(payOrder);
    }

    /**
     * 扣次处理
     *
     * @param payDto
     * @return
     */
    @SneakyThrows
    @PostMapping(value = "/deductCard")
    public Result<?> deductCard(@RequestBody PayDto payDto) {
        //处理次卡扣次逻辑
        QueryWrapper<SmtOnceCardUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_id", payDto.getCardId());
        SmtOnceCardUsers cardUsers = smtOnceCardUsersService.getOne(queryWrapper);
        if (cardUsers == null) {
            return Result.error("用户次卡信息不存在");
        }
        Integer cardNum = cardUsers.getCardRest() - payDto.getCount();
        if ((cardUsers.getCardRest() - payDto.getCount()) < 0) {
            return Result.error(606, "次卡剩余次数不足！");
        }
        UpdateWrapper<SmtOnceCardUsers> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("card_rest", cardNum);
        updateWrapper.eq("card_id", payDto.getCardId());
        //更新次卡剩余次数
        smtOnceCardUsersService.update(updateWrapper);

        PayOrder payOrder = new PayOrder();
        //生成订单编号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNo = MD5Util.encryptMd5(simpleDateFormat.format(new Date()) + RandomUtil.randomNumbers(10));
        BeanUtils.copyProperties(payDto, payOrder);
        payOrder.setUserId(payDto.getUid());
        payOrder.setTrkName("扣次项目");
        payOrder.setOrderType(7);
        payOrder.setPayPrice(payDto.getPayPrice());
        payOrder.setOrderNo(orderNo);
        payOrder.setMerchantId(payDto.getMerId());
        payOrder.setYuyueId(payDto.getYuYueId());
        payOrder.setPayTime(new Date());
        payOrder.setPayStatus("2");
        payOrder.setPayType("SCard");
        //添加扣次记录
        SmtOnceCardDeduction smtOnceCardDeduction = new SmtOnceCardDeduction();
        smtOnceCardDeduction.setOrderRest(payDto.getCount());
        smtOnceCardDeduction.setOrderNo(payOrder.getOrderNo());
        smtOnceCardDeduction.setCardId(payDto.getCardId());
        smtOnceCardDeduction.setCardName(cardUsers.getCardName());
        smtOnceCardDeduction.setMerchantId(cardUsers.getMerchantId());
        smtOnceCardDeduction.setUserId(cardUsers.getUserId());
        smtOnceCardDeduction.setUserNickname(cardUsers.getUserNickname());
        smtOnceCardDeductionService.save(smtOnceCardDeduction);
        //查询排期并占位
        SmtYuyueList yuyueList = yuyueListService.getById(payDto.getYuYueId());
        if (payDto.getCount() > (yuyueList.getCount() - yuyueList.getNum())) {
            return Result.error(606, "当前排期人数已满，请选择其他排期！");

        }
        if (yuyueList.getStartTime().compareTo(new Date()) < 1) {
            return Result.error(606, "游戏已经开始无法加入");
        }
        Integer num = yuyueList.getNum() + payDto.getCount();
        yuyueList.setNum(num);
        //更新排期
        yuyueListService.updateById(yuyueList);
        //保存收银台玩家信息与排期关联
        payDto.setOrderCouponNo(payOrder.getOrderNo());
        payDto.setOrd(yuyueList.getOrd());
        payDto.setQrCode(yuyueList.getQrCode());
        yuyueUserService.saveUser(payDto);
        //保存订单
        payOrderService.save(payOrder);
        return Result.OK("添加成功！");
    }


}
